package com.likan.chqjtgc.fallbacks;

import com.netflix.hystrix.exception.HystrixTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 *
 * 网关返回错误异常配置
 */
@Component
@Slf4j
public class ServiceFallbackProvider implements FallbackProvider {
    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        if (cause instanceof HystrixTimeoutException) {
            log.error(DateTime.now().toString()+",hystrix 限流熔断或超时fallback配置,路由:"+route+",原因："+cause.getMessage() );
            return response(HttpStatus.GATEWAY_TIMEOUT);
        } else {
            log.error(DateTime.now().toString()+",网关请求服务错误,路由:"+route+",原因："+cause.getMessage() );
            return fallbackResponse();
        }
    }


    private ClientHttpResponse fallbackResponse() {
        return response(HttpStatus.INTERNAL_SERVER_ERROR);
    }
//
//
//    public ClientHttpResponse fallbackResponse(Throwable cause) {
//        if (cause instanceof HystrixTimeoutException) {
//            return response(HttpStatus.GATEWAY_TIMEOUT);
//        } else {
//            return fallbackResponse();
//        }
//    }


    private ClientHttpResponse response(final HttpStatus status) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode()  {
                return status;
            }

            @Override
            public int getRawStatusCode()  {
                return status.value();
            }

            @Override
            public String getStatusText()  {
                return status.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody()  {
                return new ByteArrayInputStream("{\"message\":\"服务故障或超时，请稍后重试!\",\"code\":504}".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
